package com.example.frameboot.common;

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @title:身份证
 * @description:身份证相关规则
 * @author:changjb@centaline.com.cn
 * @version:2.0
 * @create 2020/1/19 14:34
 */
@Slf4j
public class IdCardUtils {

    /**
     * 每位加权因子
     */
    private static final int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    private static final Map<String, String> cityCodes = new HashMap<String, String>();
    /**
     * 台湾身份首字母对应数字
     */
    private static final Map<String, Integer> twFirstCode = new HashMap<String, Integer>();
    /**
     * 香港身份首字母对应数字
     */
    private static final Map<String, Integer> hkFirstCode = new HashMap<String, Integer>();

    static {
        cityCodes.put("11", "北京");
        cityCodes.put("12", "天津");
        cityCodes.put("13", "河北");
        cityCodes.put("14", "山西");
        cityCodes.put("15", "内蒙古");
        cityCodes.put("21", "辽宁");
        cityCodes.put("22", "吉林");
        cityCodes.put("23", "黑龙江");
        cityCodes.put("31", "上海");
        cityCodes.put("32", "江苏");
        cityCodes.put("33", "浙江");
        cityCodes.put("34", "安徽");
        cityCodes.put("35", "福建");
        cityCodes.put("36", "江西");
        cityCodes.put("37", "山东");
        cityCodes.put("41", "河南");
        cityCodes.put("42", "湖北");
        cityCodes.put("43", "湖南");
        cityCodes.put("44", "广东");
        cityCodes.put("45", "广西");
        cityCodes.put("46", "海南");
        cityCodes.put("50", "重庆");
        cityCodes.put("51", "四川");
        cityCodes.put("52", "贵州");
        cityCodes.put("53", "云南");
        cityCodes.put("54", "西藏");
        cityCodes.put("61", "陕西");
        cityCodes.put("62", "甘肃");
        cityCodes.put("63", "青海");
        cityCodes.put("64", "宁夏");
        cityCodes.put("65", "新疆");
        cityCodes.put("71", "台湾");
        cityCodes.put("81", "香港");
        cityCodes.put("82", "澳门");
        cityCodes.put("91", "国外");
        twFirstCode.put("A", 10);
        twFirstCode.put("B", 11);
        twFirstCode.put("C", 12);
        twFirstCode.put("D", 13);
        twFirstCode.put("E", 14);
        twFirstCode.put("F", 15);
        twFirstCode.put("G", 16);
        twFirstCode.put("H", 17);
        twFirstCode.put("J", 18);
        twFirstCode.put("K", 19);
        twFirstCode.put("L", 20);
        twFirstCode.put("M", 21);
        twFirstCode.put("N", 22);
        twFirstCode.put("P", 23);
        twFirstCode.put("Q", 24);
        twFirstCode.put("R", 25);
        twFirstCode.put("S", 26);
        twFirstCode.put("T", 27);
        twFirstCode.put("U", 28);
        twFirstCode.put("V", 29);
        twFirstCode.put("X", 30);
        twFirstCode.put("Y", 31);
        twFirstCode.put("W", 32);
        twFirstCode.put("Z", 33);
        twFirstCode.put("I", 34);
        twFirstCode.put("O", 35);
        hkFirstCode.put("A", 1);
        hkFirstCode.put("B", 2);
        hkFirstCode.put("C", 3);
        hkFirstCode.put("R", 18);
        hkFirstCode.put("U", 21);
        hkFirstCode.put("Z", 26);
        hkFirstCode.put("X", 24);
        hkFirstCode.put("W", 23);
        hkFirstCode.put("O", 15);
        hkFirstCode.put("N", 14);
    }

    /**
     * 验证18位大陆身份证编码是否合法
     *
     * @param idcard 身份编码
     * @return true 代表合法
     * <p>
     * - 是否合法(合法true,不合法false)
     */
    public static boolean validateIdCard18(String idcard) throws Exception {
        String regularExpression;
        // 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
        regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";

        boolean matches = idcard.matches(regularExpression);

        //判断第18位校验值
        if (matches) {
            char[] charArray = idcard.toCharArray();
            //前十七位加权因子
            int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
            //这是除以11后，可能产生的11位余数对应的验证码
            String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
            int sum = 0;
            for (int i = 0; i < idCardWi.length; i++) {
                int current = Integer.parseInt(String.valueOf(charArray[i]));
                int count = current * idCardWi[i];
                sum += count;
            }
            char idCardLast = charArray[17];
            int idCardMod = sum % 11;
            if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
                return true;
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }
        }

        return true;
    }

    /**
     * 验证10位身份证编码是否合法
     *
     * @param idcard 身份编码
     * @return true 代表合法
     * <p>
     * [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
     */
    public static boolean validateIdCard10(String idcard) throws Exception {
        String regularExpressionTw;
        String regularExpressionHk;
        String regularExpressionMo;
        String[] info = new String[3];
        String card = idcard.replaceAll("[\\(|\\)]", "");
        if (card.length() != 8 && card.length() != 9 && idcard.length() != 10) {
            return false;
        }
        regularExpressionTw = "^[a-zA-Z][0-9]{9}";
        regularExpressionMo = "^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$";
        regularExpressionHk = "^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$";
        if (idcard.matches(regularExpressionTw)) {
            info[0] = "台湾";
            String charSex = idcard.substring(1, 2);
            if (charSex.equals("1")) {
                info[1] = "M";
            } else if (charSex.equals("2")) {
                info[1] = "F";
            } else {
                info[1] = "N";
                info[2] = "false";
            }
            info[2] = validateTWCard(idcard) ? "true" : "false";
        } else if (idcard.matches(regularExpressionMo)) {
            info[0] = "澳门";
            info[1] = "N";
        } else if (idcard.matches(regularExpressionHk)) {
            info[0] = "香港";
            info[1] = "N";
            info[2] = validateHKCard(idcard) ? "true" : "false";
        } else {
            return false;
        }

        if ("false".equals(info[2])) {
            return false;
        }

        return true;
    }

    /**
     * 验证11位通行证编码是否合法
     *
     * @param idcard 通行证编码
     * @return true 代表合法
     */
    public static boolean validatePassCard(String idcard) throws Exception {
        String regularExpressionPassCard;
        String[] info = new String[3];
        String card = idcard.replaceAll("[\\(|\\)]", "");
        if (card.length() != 9 && idcard.length() != 11) {
            return false;
        }

        regularExpressionPassCard = "^[HM]{1}\\([0-9]{10}\\)$";
        if (idcard.matches(regularExpressionPassCard)) {
            info[0] = "香港";
            String soureType = idcard.substring(1, 1);
            if (soureType.equals("H")) {
                info[0] = "香港";
            } else if (soureType.equals("M")) {
                info[0] = "澳门";
            } else {
                return false;
            }
        } else {
            return false;
        }

        return true;
    }

    /**
     * 根据身份编号获取户籍省份
     *
     * @param idcard 身份编码
     * @return 省级编码。
     */
    public static String getProvinceByIdCard(String idcard) throws Exception {
        int len = idcard.length();
        if (len != 18) {
            throw new Exception("未知身份证！");
        }
        String province;
        String provinceCode;
        provinceCode = idcard.substring(0, 2);
        province = cityCodes.get(provinceCode);
        return province;
    }


    /**
     * 验证台湾身份证号码
     * 共10位
     * 计算校验码的步骤：1、英文转成数字，其个位数字*9+十位数
     * 2、中间八位数字，各数字从左到右依次乘以8、7、6、5....2、1
     * 3、计算步骤1和2的和sum
     * 4、计算10-sum%10 ,其结果就是检查码，若余数为0，则检查码就是0
     *
     * @param idcard 身份证号码
     * @return 验证码是否符合
     */
    public static boolean validateTWCard(String idcard) {
        //第一位是字母（表示地区代码），通过map找到对应的数字代码
        String start = idcard.substring(0, 1);
        //第二位数字表示性别，男生为1，女生为2
        String mid = idcard.substring(1, 9);
        //最后一位是检查码,由第一位和8个数字的组合计算得到校验和
        String end = idcard.substring(9, 10);
        Integer iStart = twFirstCode.get(start);

        Integer sum = iStart / 10 + (iStart % 10) * 9;
        char[] chars = mid.toCharArray();
        Integer countFlag = 8;
        for (char c : chars) {
            sum = sum + Integer.valueOf(c + "") * countFlag;
            countFlag--;
        }
        return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false;
    }

    /**
     * 验证香港身份证号码(存在Bug，部份特殊身份证无法检查)
     * <p>
     * 如：身份证号码是：C668668（9）
     * 香港身份证号码由三部分组成：一个英文字母；6个数字；括号及0-9中的任一个数字，或者字母A。
     * 括号中的数字或字母A，是校验码，用于检验括号前面的号码的逻辑正确性。
     * <p>
     * 身份证前2位为英文字符，如果只出现一个英文字符则表示第一位是空格，对应数字58, 前2位英文字符A-Z分别对应数字10-35
     * 最后一位校验码为0-9的数字加上字符"A"，"A"代表10
     * 将身份证号码全部转换为数字，分别对应乘9、8...1相加的总和，整除11则证件号码有效
     *
     * @param idcard 身份证号码
     * @return 验证码是否符合
     */
    public static boolean validateHKCard(String idcard) {
        String card = idcard.replaceAll("[\\(|\\)]", "");
        Integer sum = 0;
        if (card.length() == 9) {
            sum = (Integer.valueOf(card.substring(0, 1).toUpperCase()
                    .toCharArray()[0]) - 55)
                    * 9
                    + (Integer.valueOf(card.substring(1, 2).toUpperCase()
                    .toCharArray()[0]) - 55) * 8;
            card = card.substring(1, 9);
        } else {
            sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase()
                    .toCharArray()[0]) - 55) * 8;
        }
        String mid = card.substring(1, 7);
        String end = card.substring(7, 8);
        char[] chars = mid.toCharArray();
        Integer countFlag = 7;
        for (char c : chars) {
            sum = sum + Integer.valueOf(c + "") * countFlag;
            countFlag--;
        }
        if (end.toUpperCase().equals("A")) {
            sum = sum + 10;
        } else {
            sum = sum + Integer.valueOf(end);
        }
        return (sum % 11 == 0) ? true : false;
    }


    /**
     * 根据身份编号获取生日
     *
     * @param idCard 身份编号
     * @return 生日(yyyyMMdd)
     */
    public static String getBirthByIdCard(String idCard) throws Exception {
        if (idCard == null) {
            throw BusinessException
                    .builder()
                    .code(HttpStatusEnum.ID_CARD_NOT_EMPTY.getCode())
                    .message(HttpStatusEnum.ID_CARD_NOT_EMPTY.getMessage())
                    .build();
        } else {
            Integer len = idCard.length();
            if (len < 15 || len > 18) {
                return null;
            } else if (len == 15) {
                idCard = conver15CardTo18(idCard);
            }

            if (idCard != null && idCard.length() == 18) {
                return idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }

        }
    }

    /**
     * 将15位身份证号码转换为18位
     *
     * @param idCard 15位身份编码
     * @return 18位身份编码
     */
    public static String conver15CardTo18(String idCard) {
        String idCard18 = "";
        if (idCard.length() != 15) {
            return null;
        }

        if (isNum(idCard)) {
            // 获取出生年月日
            String birthday = idCard.substring(6, 12);
            Date birthDate = null;

            try {
                birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            Calendar cal = Calendar.getInstance();

            if (birthDate != null) {
                cal.setTime(birthDate);
            }

            // 获取出生年(完全表现形式,如：2010)
            String sYear = String.valueOf(cal.get(Calendar.YEAR));
            idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8);

            // 转换字符数组

            char[] cArr = idCard18.toCharArray();
            if (cArr != null) {
                int[] iCard = converCharToInt(cArr);
                int iSum = getPowerSum(iCard);
                // 获取校验位
                String sVal = getCheckCode18(iSum);

                if (sVal.length() > 0) {

                    idCard18 += sVal;
                } else {
                    return null;

                }
            }
        } else {
            return null;

        }

        return idCard18;

    }


    /**
     * 将字符数组转换成数字数组
     *
     * @param ca 字符数组
     * @return 数字数组
     */
    public static int[] converCharToInt(char[] ca) {
        int len = ca.length;
        int[] iArr = new int[len];
        try {
            for (int i = 0; i < len; i++) {
                iArr[i] = Integer.parseInt(String.valueOf(ca[i]));
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }
        return iArr;
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后，再得到和值
     *
     * @param iArr
     * @return 身份证编码。
     */
    public static int getPowerSum(int[] iArr) {
        int iSum = 0;
        if (power.length == iArr.length) {
            for (int i = 0; i < iArr.length; i++) {
                for (int j = 0; j < power.length; j++) {
                    if (i == j) {
                        iSum = iSum + iArr[i] * power[j];
                    }
                }
            }
        }
        return iSum;
    }

    /**
     * 将power和值与11取模获得余数进行校验码判断
     *
     * @param iSum
     * @return 校验位
     */
    public static String getCheckCode18(int iSum) {
        String sCode = "";
        switch (iSum % 11) {
            case 10:
                sCode = "2";
                break;
            case 9:
                sCode = "3";
                break;
            case 8:
                sCode = "4";
                break;
            case 7:
                sCode = "5";
                break;
            case 6:
                sCode = "6";
                break;
            case 5:
                sCode = "7";
                break;
            case 4:
                sCode = "8";
                break;
            case 3:
                sCode = "9";
                break;
            case 2:
                sCode = "x";
                break;
            case 1:
                sCode = "0";
                break;
            case 0:
                sCode = "1";
                break;
        }
        return sCode;
    }


    /**
     * 根据身份编号获取生日年
     *
     * @param idCard 身份编号
     * @return 生日(yyyy)
     */
    public static Short getYearByIdCard(String idCard) {
        if (idCard == null) {
            throw BusinessException
                    .builder()
                    .code(HttpStatusEnum.ID_CARD_NOT_EMPTY.getCode())
                    .message(HttpStatusEnum.ID_CARD_NOT_EMPTY.getMessage())
                    .build();
        } else {
            Integer len = idCard.length();
            if (len < 15 || len > 18) {
                return null;
            } else if (len == 15) {
                idCard = conver15CardTo18(idCard);
            }

            if (idCard != null && idCard.length() == 18) {
                return Short.valueOf(idCard.substring(6, 10));
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }

        }
    }

    /**
     * 根据身份编号获取生日月
     *
     * @param idCard 身份编号
     * @return 生日(MM)
     */
    public static Short getMonthByIdCard(String idCard) {
        if (idCard == null) {
            throw BusinessException
                    .builder()
                    .code(HttpStatusEnum.ID_CARD_NOT_EMPTY.getCode())
                    .message(HttpStatusEnum.ID_CARD_NOT_EMPTY.getMessage())
                    .build();
        } else {
            Integer len = idCard.length();
            if (len < 15 || len > 18) {
                return null;
            } else if (len == 15) {
                idCard = conver15CardTo18(idCard);
            }

            if (idCard != null && idCard.length() == 18) {
                return Short.valueOf(idCard.substring(10, 12));
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }


        }
    }

    /**
     * 根据身份编号获取生日天
     *
     * @param idCard 身份编号
     * @return 生日(dd)
     */
    public static Short getDateByIdCard(String idCard) {
        if (idCard == null) {
            throw BusinessException
                    .builder()
                    .code(HttpStatusEnum.ID_CARD_NOT_EMPTY.getCode())
                    .message(HttpStatusEnum.ID_CARD_NOT_EMPTY.getMessage())
                    .build();
        } else {
            Integer len = idCard.length();
            if (len < 15 || len > 18) {
                return null;
            } else if (len == 15) {
                idCard = conver15CardTo18(idCard);
            }

            if (idCard != null && idCard.length() == 18) {
                return Short.valueOf(idCard.substring(12, 14));
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }


        }
    }

    /**
     * 根据身份编号获取性别
     *
     * @param idCard 身份编号
     * @return 性别(M - 男 ， F - 女 ， N - 未知)
     */
    public static String getGenderByIdCard(String idCard) {
        if (idCard == null) {
            throw BusinessException
                    .builder()
                    .code(HttpStatusEnum.ID_CARD_NOT_EMPTY.getCode())
                    .message(HttpStatusEnum.ID_CARD_NOT_EMPTY.getMessage())
                    .build();
        } else {
            String sGender = "N";
            if (idCard.length() == 15) {
                idCard = conver15CardTo18(idCard);
            }

            if (idCard != null && idCard.length() == 18) {
                String sCardNum = idCard.substring(16, 17);
                if (Integer.parseInt(sCardNum) % 2 != 0) {
                    sGender = "M";
                } else {
                    sGender = "F";
                }
                return sGender;
            } else {
                throw BusinessException
                        .builder()
                        .code(HttpStatusEnum.IDCARD18_ERROR.getCode())
                        .message(HttpStatusEnum.IDCARD18_ERROR.getMessage())
                        .build();
            }


        }
    }


    /**
     * 数字验证
     *
     * @param val
     * @return 提取的数字。
     */
    public static boolean isNum(String val) {
        return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
    }

    /**
     * 验证小于当前日期 是否有效
     *
     * @param iYear  待验证日期(年)
     * @param iMonth 待验证日期(月 1-12)
     * @param iDate  待验证日期(日)
     * @return 是否有效
     */
    public static boolean valiDate(int iYear, int iMonth, int iDate) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int datePerMonth;
        if (iYear < 1900 || iYear >= year) {
            return false;
        }
        if (iMonth < 1 || iMonth > 12) {
            return false;
        }
        switch (iMonth) {
            case 4:
            case 6:
            case 9:
            case 11:
                datePerMonth = 30;
                break;
            case 2:
                boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0)) && (iYear > 1900 && iYear < year);
                datePerMonth = dm ? 29 : 28;
                break;
            default:
                datePerMonth = 31;
        }
        return (iDate >= 1) && (iDate <= datePerMonth);
    }

}
